package com.colter.project.sample.test.plan.english;

import com.colter.project.util.string.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EnglishFillTemplate {
	public static void main(String[] args) {
		List<Plan> list = null;
		try {
			list = getFromTxt();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		File file = new File(prefix + "plan.xlsx");
		if (!file.exists()) {
			System.out.println("请先生成" + file.getAbsolutePath());
		}
		if (list == null || list.size() == 0) {
			System.out.println("没有需要填充的计划列表.");
			return;
		}

		Workbook wb = null;
		Sheet sheet = null;
		Row row = null;
		Cell cell = null;

		boolean isXlsx = file.getAbsolutePath().endsWith("xlsx");
		try {
			if (isXlsx) {
				wb = new XSSFWorkbook(new FileInputStream(file));
			} else {
				wb = new HSSFWorkbook(new FileInputStream(file));
			}

			boolean isChange = false;
			sheet = wb.getSheetAt(0);
			for (int i = 0; i < list.size(); i++) {
				Plan plan = list.get(i);
				for (int j = 0; j < sheet.getLastRowNum(); j++) {
					row = sheet.getRow(j);
					if (row.getCell(1) != null && row.getCell(1).getStringCellValue().equals(plan.date)) {
						for (int k = 2; k < row.getLastCellNum(); k++) {
							cell = row.getCell(k);
							if (cell != null) {
								isChange = changeValue(wb, sheet, cell, j, plan, k);
							}
							if (isChange) {
								break;
							}
						}
						break;
					}

					if (isChange) {
						isChange = !isChange;
						break;
					}

				}
				System.out.println("next");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 输出Excel文件
		FileOutputStream output;
		try {
			output = new FileOutputStream(file);
			wb.write(output);
			output.flush();
			wb.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static boolean changeValue(Workbook wb, Sheet sheet, Cell cell, int j, Plan plan, int k) {
		try {
			boolean isFirst = false;

			Row r2 = sheet.getRow(j + 1);
			Cell cell2 = r2.getCell(k);

			Row r4 = sheet.getRow(j + 3);
			Cell cell4 = r4.getCell(k);

			Row r7 = sheet.getRow(j + 6);
			Cell cell7 = r7.getCell(k);

			Row r15 = sheet.getRow(j + 14);
			Cell cell15 = r15.getCell(k);

			isFirst = (int) cell2.getNumericCellValue() == (int) cell.getNumericCellValue()
					&& (int) cell4.getNumericCellValue() == (int) cell.getNumericCellValue()
					&& (int) cell7.getNumericCellValue() == (int) cell.getNumericCellValue()
					&& (int) cell15.getNumericCellValue() == (int) cell.getNumericCellValue();
			if (isFirst) {
				if (plan.link != null) {
					CellStyle style = wb.createCellStyle();
					Font font = wb.createFont();
					font.setColor(IndexedColors.BLUE.getIndex());
					style.setFont(font);
					CreationHelper createHelper = wb.getCreationHelper();
					
					int linkType = Hyperlink.LINK_URL;
					if(plan.isFile){
						linkType = Hyperlink.LINK_FILE;
					}
					
					Hyperlink link = createHelper.createHyperlink(linkType);
					link.setAddress(plan.link);
					
					Hyperlink link2 = createHelper.createHyperlink(linkType);
					link2.setAddress(plan.link);
					
					Hyperlink link4 = createHelper.createHyperlink(linkType);
					link4.setAddress(plan.link);
					
					Hyperlink link7 = createHelper.createHyperlink(linkType);
					link7.setAddress(plan.link);
					
					Hyperlink link15 = createHelper.createHyperlink(linkType);
					link15.setAddress(plan.link);

					cell.setCellStyle(style);
					cell.setCellValue(plan.value);
					cell.setHyperlink(link);

					cell2.setCellStyle(style);
					cell2.setCellValue(plan.value);
					cell2.setHyperlink(link2);

					cell4.setCellStyle(style);
					cell4.setCellValue(plan.value);
					cell4.setHyperlink(link4);

					cell7.setCellStyle(style);
					cell7.setCellValue(plan.value);
					cell7.setHyperlink(link7);

					cell15.setCellStyle(style);
					cell15.setCellValue(plan.value);
					cell15.setHyperlink(link15);

				} else {
					cell.setCellValue(plan.value);
					cell2.setCellValue(plan.value);
					cell4.setCellValue(plan.value);
					cell7.setCellValue(plan.value);
					cell15.setCellValue(plan.value);
				}

				System.out.println("修改了对应的值：" + plan + "第几行：" + j + "第几列：" + k);
				return true;
			}
		} catch (NullPointerException | IllegalStateException e) {
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	public static String getPrefix() {
		String re = "c:\\";
		String path = re;
		try {
			path = URLDecoder.decode(EnglishFillTemplate.class.getProtectionDomain().getCodeSource().getLocation().getPath(),
					"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println("path:" + path);
		File f = new File(path);
		if (f.exists()) {
			re = f.getParent() + "\\";
		}
		System.out.println("文件路径：" + re);
		return re;
	}

	public static String prefix = getPrefix();

	public static List<Plan> getFromTxt() throws IOException, ParseException {
		File file = new File(prefix + "plan.txt");
		BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

		List<String> list = new ArrayList<>();
		String temp = null;
		while ((temp = bf.readLine()) != null) {
			if (StringUtils.trimToNull(temp) == null) {
				continue;
			}
			list.add(temp);
		}
		SimpleDateFormat sd = new SimpleDateFormat("MM-dd", Locale.US);
		SimpleDateFormat sd2 = new SimpleDateFormat(EnglishCreateTemplate.getMonth(), EnglishCreateTemplate.geteLocale());
		System.out.println("List:"+list);
		bf.close();
		List<Plan> plans = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			String str = list.get(i);
			if (isDate(str)) {
				int j = i + 1;
				if (j < list.size()) {
					String str2 = list.get(j);
					if (!isDate(str2)) {
						i++;

						Plan plan = new Plan();
						String date = sd2.format(sd.parse(str));
						plan.date = date;
						if (str2.indexOf("url") != -1) {
							String[] tv = str2.split("url");
							plan.value = StringUtils.trim(tv[0]);
							plan.link = StringUtils.trimToNull(tv[1]);
							plan.isFile = false;
						} else if(str2.indexOf("file") != -1){
							String[] tv = str2.split("file");
							plan.value = StringUtils.trim(tv[0]);
							File file2 = new File(StringUtils.trim(tv[1]));
							System.out.println(file2.exists());
							//plan.link = URLDecoder.decode(URLEncoder.encode(StringUtils.trim(tv[1]),"utf-8"),"utf-8");
							plan.link =StringUtils.trimToNull(tv[1].replace("\\", "/"));
							plan.isFile = true;
						} else{
							plan.value = str2;
						}
						plans.add(plan);
						System.out.println(plan);
					}
				}
			}

		}

		return plans;
	}

	public static boolean isDate(String str) {
		Pattern pattern = Pattern.compile("^\\d{2}-{1}\\d{2}$");
		Matcher m = pattern.matcher(str);
		return m.find();
	}

}

class Plan {
	public String date;
	public String value;
	public String link;
	public boolean isFile;

	@Override
	public String toString() {
		return "Plan [date=" + date + ", value=" + value + ", link=" + link + ", isFile=" + isFile + "]";
	}

}
